package com.springmvc.controller;

import com.springmvc.constant.QueryConstant;
import com.springmvc.entity.User;
import com.springmvc.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 */
@Controller
@RequestMapping("login")
public class LoginController {

    private static final Logger log = Logger.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("index")
    public String login() {
        log.info("进入到登录页面!");
        return "sys/login";
    }

    @ResponseBody
    @RequestMapping("userLogin")
    public Map<String,Object> userLogin(User user, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = userService.getLoginInfo(user);
            String code = String.valueOf(map.get("code"));
            if ("1".equals(code)) {
                request.getSession().setAttribute("LOGIN_USER",user.getLoginName());
            }
        } catch (Exception e) {
            map.put("code", QueryConstant.FAIL_CODE);
            map.put("msg", e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("userLogout")
    public Map<String, Object> userLogout(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            request.getSession().removeAttribute("LOGIN_USER");
            request.getSession().invalidate();
            map.put("code", QueryConstant.SUCCESS_CODE);
            map.put("msg", QueryConstant.LOGOUT_SUCCESS_MSG);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", QueryConstant.FAIL_CODE);
            map.put("msg", e.getMessage());
        }
        return map;
    }

    /**
     * 跳转菜单页
     * @return
     */
    @RequestMapping("menu")
    public String menu() {
        log.info("进入到菜单页面!");
        return "sys/menu";
    }
}
